<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 汪利东,2016-04-08 16:19
// +----------------------------------------------------------------------
namespace Admin\Controller;
class CardController extends BaseController {

    public function index() {
        $mapstr='';
        $card_id = I('get.card_id');
        if (!empty($card_id)) {
            $mapstr='card_id="'.$card_id.'"';
        }
        $keywords = I('get.keywords');
        if (!empty($keywords)) {
            if($mapstr==''){
                $mapstr.='(card_id="'.$keywords.'" or mobile like "'.$keywords.'")';
            }else{
                $mapstr.=' AND (card_id="'.$keywords.'" or mobile like "'.$keywords.'")';
            }
        }
        $valid=I('get.valid');
        switch($valid){
            case "0":break;
            case "1":
                //有效
                if($mapstr==''){
                    $mapstr.='(expire_time >"'.date('Y-m-d H:i:s').'")';
                }else{
                    $mapstr.=' AND (expire_time >"'.date('Y-m-d H:i:s').'")';
                }
                break;
            case "2":
                //无效会员
                if($mapstr==''){
                    $mapstr.='(expire_time <"'.date('Y-m-d H:i:s').'")';
                }else{
                    $mapstr.=' AND (expire_time <"'.date('Y-m-d H:i:s').'")';
                }
                break;
            default:break;
        }
        $count = D('Card')->where($mapstr)->count();// 查询满足要求的总记录数
        $Page = new  \Admin\Common\Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $data = D('Card')->relation(TRUE)->where($mapstr)->limit($Page->firstRow . ',' . $Page->listRows)->order('card_id')->select();
        $this->data = $data;
        $this->display();
    }

    //冻结
    function lock() {
        $card_id = I("get.card_id");
        $Card = M("Card");
        $Card->startTrans();
        $d = $Card->where(["card_id" => $card_id])->save(["is_lock" => -1]);
        if ($d != FALSE) {
            $Card->commit();
            $this->success("冻结成功" , U("index"));
        } else {
            $Card->rollback();
            $this->error("冻结失败");
        }
    }

    //解冻
    function unlock() {
        $card_id = I("get.card_id");
        $Card = M("Card");
        $Card->startTrans();
        $d = $Card->where(["card_id" => $card_id])->save(["is_lock" => 0]);
        if ($d != FALSE) {
            $Card->commit();
            $this->success("解冻成功" , U("index"));
        } else {
            $Card->rollback();
            $this->error("解冻失败");
        }
    }

    //注销
    function cancel(){
        $card_id = I("get.card_id");
        $Card = M("Card");
        $c = $Card->where(["card_id" => $card_id])->find();
        $orderCount = M("order_book")->where(["user_id"=>$c["user_id"]])->count();
        if($orderCount !=0){
            $this->error("注销失败！该会员卡下有订单，不能注销！");
            return;
        }
        $Card->startTrans();
        $del1 = $Card->where(["card_id" => $card_id])->delete();
        $del2 = M("user")->where(["user_id"=>$c["user_id"]])->delete();
        if ($del1 && $del2) {
            $Card->commit();
            $this->success("注销成功！" , U("index"));
        } else {
            $Card->rollback();
            $this->error("注销失败！");
        }

    }
    //获取会员卡信息
    function getinfo(){
        $card_id=I("post.card_id");
        $d=M("Card")->where(["card_id"=>$card_id])->find();
        if(!$d){
            $r=[
                "status"=>"error",
                "data"=>"会员卡不存在"
            ];
            echo json_encode($r);
            return;
        }
        $time=time();
        if(strtotime($d['create_time']) > $time  || $time > strtotime($d['expire_time'])){
            //过期
            $d["num_delivery"]=0;
            $d["num_activity"]=0;
            $d["discount_apply"]=1;
            $d["discount_buy"]=1;
            $d["is_overdue"]=1;
        }
        if($d['is_lock'] == -1){
            //已冻结
            $d['is_lock'] ="冻结";
            $d["num_delivery"]=0;
            $d["num_activity"]=0;
            $d["discount_apply"]=1;
            $d["discount_buy"]=1;
        }else{
            $d['is_lock'] ="正常";
        }
        if($d['delay_time']==""){
            $d['delay_time']=[
                'start_time'=>'',
                'end_time'=>''
            ];
        }else{
            $d['delay_time']=json_decode($d['delay_time']);
        }

        $r=[
            "status"=>"success",
            "data"=>$d
        ];
        echo json_encode($r);
        return;
    }

    //会员卡充值类型
    function type_search(){
        $type_id=I("post.type_id");
        $d=M("Deposit_type")->where(["type_id"=>$type_id])->find();
        $r=[
            "status"=>"success",
            "data"=>$d
        ];
        echo json_encode($r);
    }

    //excel-批量导入会员卡及新建用户
    public function import() {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Card = M('Card');
            $Card->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            unset($data[0]);
            $row=1;
            foreach ($data as $k => $v) {
                $save = NULL;
                //插入
                foreach ($colname as $key => $value) {
                    if($v[ $key ]==''){
                        continue;
                    }
                    switch($value){
                        case 'create_time':
                        case 'expire_time':
                        case 'child_birth':$save[ $value ]=convert_etimetoptime($v[ $key ]);break;
                        default:$save[ $value ] = (string)$v[ $key ];break;
                    }
                }
                if($save==null){
                    continue;
                }
                $row++;
                if($save['child_name']==''){
                    $Card->rollback();
                    $this->error('导入出错,小孩姓名不可为空,错误发生在第'.$row.'行');
                }
                if($save['card_id']==''){
                    $Card->rollback();
                    $this->error('导入出错,会员卡号不可为空,错误发生在第'.$row.'行');
                }

                $du=[
                    'nickname'=>$save['child_name']
                ];
                $user_id=M('User')->data($du)->add();
                if(!$user_id){
                    $Card->rollback();
                    $this->error('导入错误,新建用户出错,错误发生在第'.$row.'行');
                }
                $save['user_id']=$user_id;
                $c=$Card->where(['card_id'=>$save['card_id']])->count();
                if($c>0){
                    $Card->rollback();
                    $this->error('导入错误,已有会员卡存在,错误发生在第'.$row.'行,card_id:'.$save['card_id']);
                }
                $card_id=$Card->data($save)->add();
                if(!$card_id){
                    $Card->rollback();
                    $this->error('导入错误,会员卡新建失败,错误发生在第'.$row.'行');
                }
                $content='批量会员卡导入,导入信息:';
                foreach($save as $k=>$v){
                    $content.=$k.':'.$v.';';
                }
                $log=[
                    'user_id'=>session('admin_user.user_id'),
                    'content'=>$content
                ];
                $log_id=M('admin_stocklog')->data($log)->add();//库存管理日志
                if(!$log_id){
                    $Card->rollback();
                    $this->error('导入失败,日志记录出错,错误发生在第'.$row.'行');
                }
            }
            $Card->commit();
        }
        //        echo '操作成功';
        $this->success('操作成功');
    }
    //批量会员卡充值
    function importDeposit(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = ['xls' , 'xlsx'];// 设置附件上传类型
        $upload->rootPath = './uploads/excel/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->autoSub = FALSE;
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功
            $Card = M('Card');
            $Card->startTrans();
            $data = excel_import($upload->rootPath . $info["excel"]["savename"] , $info["excel"]['ext']);
            //第一行为字段
            $colname = $data[0];
            unset($data[0]);
            $row=0;
            foreach ($data as $k => $v) {
                $save = NULL;
                //插入
                foreach ($colname as $key => $value) {
                    if($v[ $key ]==''){
                        continue;
                    }
                    switch($value){
                        default:$save[ $value ] = (string)$v[ $key ];break;
                    }
                }
                if($save==null){
                    continue;
                }
                $row++;
                if($save['type_id']==''){
                    $Card->rollback();
                    $this->error('导入出错,充值类型不可为空,错误发生在第'.$row.'行');
                }
                if($save['card_id']==''){
                    $Card->rollback();
                    $this->error('导入出错,会员卡号不可为空,错误发生在第'.$row.'行');
                }
                //查询会员卡信息
                $dc=$Card->where(['card_id'=>$save['card_id']])->find();
                if(!$dc){
                    $Card->rollback();
                    $this->error('导入出错,会员卡号不存在,错误发生在第'.$row.'行');
                }
                //查询充值类型
                $DepositType = M('Deposit_type');
                $dtt=$DepositType->where(['type_id'=>$save['type_id']])->find();
                if(!$dtt){
                    $Card->rollback();
                    $this->error('导入出错,充值类型不存在,错误发生在第'.$row.'行');
                }
                //生成支付订单
                $data_pay['user_id']=$dc['user_id'];
                $data_pay['status']='1';
                $data_pay['type']='3';
                $data_pay['way']='cash';
                $data_pay['summary']='初始化批量充值,会员卡号:'.$save['card_id'].',充值类型:'.$save['type_id'];
                $data_pay['money']=$dtt['price'];
                $data_pay['money_real']=$dtt['price'];
                $Pay=M('Pay');
                $pay_id=$Pay->data($data_pay)->add();
                if(!$pay_id){
                    $Card->rollback();
                    $this->error('导入出错,生成支付订单失败,错误发生在第'.$row.'行');
                }
                //生成充值记录
                $Deposit=M('Deposit');
                $data_deposit['card_id']=$save['card_id'];
                $data_deposit['type_id']=$save['type_id'];
                $data_deposit['pay_id']=$pay_id;
                $deposit_id=$Deposit->data($data_deposit)->add();
                if(!$deposit_id){
                    $Card->rollback();
                    $this->error('导入出错,生成充值记录失败,错误发生在第'.$row.'行');
                }
                //会员卡数据更新
                if (strtotime($dc['expire_time']) < time()) {
                    $data_card["expire_time"] = date("Y-m-d h:i:s", strtotime("+" . $dtt["month"] . "months", time()));
                } else {
                    $data_card["expire_time"] = date("Y-m-d h:i:s", strtotime("+" . $dtt["month"] . "months", strtotime($dc['expire_time'])));
                }
                $data_card["num_activity"] = $dc["num_activity"] + $dtt["num_activity"];
                $data_card["num_delivery"] = $dc["num_delivery"] + $dtt["num_delivery"];
                if($dc['discount_buy']>$dtt['discount_buy']){
                    $data_card["discount_buy"] = $dtt["discount_buy"];
                }
                if($dc['discount_apply']>$dtt['discount_apply']){
                    $data_card["discount_apply"] = $dtt["discount_apply"];
                }
                $r=$Card->where(["card_id"=>$save['card_id']])->data($data_card)->save();
                if(!$r){
                    $Card->rollback();
                    $this->error('导入出错,更新会员数据失败,错误发生在第'.$row.'行');
                }
                $content='批量会员卡充值,导入信息:';
                foreach($save as $k=>$v){
                    $content.=$k.':'.$v.';';
                }
                $log=[
                    'user_id'=>session('admin_user.user_id'),
                    'content'=>$content
                ];
                $log_id=M('admin_stocklog')->data($log)->add();
                if(!$log_id){
                    $Card->rollback();
                    $this->error('导入失败,日志记录出错,错误发生在第'.$row.'行');
                }
            }
            $Card->commit();
        }
        //        echo '操作成功';
        $this->success('操作成功');
    }

    function export(){
        $Card = M('Card');

        $d = $Card->field('card_id,user_id,create_time,expire_time,num_delivery,num_activity,discount_apply,discount_buy,delay_time,father_name,father_phone,mother_name,mother_phone,child_name,child_birth,child_sex,child_school,remark')->select();
        //        var_dump($d);
        $file = excel_export($d);
        ouput_Browser($file);
    }

}